#! /bin/bash 

SERVER_HOME=`dirname $0`
SCRIPT_NAME=`basename $0`
cd ${SERVER_HOME}
SERVER_HOME=`pwd`

SERVER_BIN=${SERVER_HOME}/bin
SERVER_CONF=${SERVER_HOME}/conf
SERVER_CONF2=${SERVER_HOME}/conf2
SERVER_CONF3=${SERVER_HOME}/conf3
SERVER_LIB=${SERVER_HOME}/lib  
SERVER_3LIB=${SERVER_HOME}/../3lib
SERVER_LOG=${SERVER_HOME}/log
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${SERVER_LIB}:${SERVER_3LIB}

LOG_FILE="${SERVER_HOME}/log/${SCRIPT_NAME}.log"

. ${SERVER_HOME}/scripts/script_func.sh

if [ $# == 0 ]; then 
	echo "do you want to stop im server process ${SERVER_HOME}? [yes|no]"
	read stop_im_server
	if [ "yes" != "$stop_im_server" ]
	then
	    echo "cancel"
	    exit 0
	fi
fi



function stop_node()
{
	server_bin_files=`ls ${SERVER_BIN}/`
	for server_bin in $server_bin_files
	do
	    local CONF="${1}/${server_bin}.json"
		#echo "$CONF"
	    if [ -f "$CONF" ]
	    then
	        target_server=`awk -F'"server_name"' '/server_name/{print $2}'  ${CONF} | sed 's/ //g' | awk -F'[:",]' '{print $3}'`
	        target_port=`awk -F'"inner_port"' '/inner_port/{print $2}'  ${CONF} | sed 's/ //g' | awk -F'[:",]' '{print $2}'`
	        target_server_tag=`echo "$target_server" | awk '{print substr($0,0,10)}'`
	        #echo ${target_server_tag}
	        #echo $target_port
	        running_target_server_pid=`netstat -apn 2>>/dev/null | grep -w $target_port | grep $target_server_tag | awk -F/ '/^tcp/{print $1}' | awk '/LISTEN/{print $NF}'`
	        #echo "running_target_server_pid:$running_target_server_pid"
	        if [ -n "$running_target_server_pid" ]
	        then
	            echo "kill $running_target_server_pid    $target_server"
	            kill $running_target_server_pid
	        fi
	    fi
	done
}


if [ "$1"x == "1"x ];then
	stop_node "${SERVER_CONF}"
elif [ "$1"x == "2"x ];then
	stop_node "${SERVER_CONF2}"
elif [ "$1"x == "3"x ];then
	stop_node "${SERVER_CONF3}"
elif [ "$1"x == "all"x ];then
	stop_node "${SERVER_CONF}"
	stop_node "${SERVER_CONF2}"
	stop_node "${SERVER_CONF3}"
else
	#默认启动单个中心节点
	stop_node "${SERVER_CONF}"
	stop_node "${SERVER_CONF2}"
	stop_node "${SERVER_CONF3}"
fi
